package function.search;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import tool.StringUtils;

import boot.Boot;

public class SearchByArtist {

	private static final String ARTIST_INDEX_FOLDER = "file:///E:/_Indexes/byArtists";

	private Hashtable index = new Hashtable();
	private Artist artist;

	public SearchByArtist() {
		setup();
	}

	private void setup() {

		FileConnection connection;
		try {
			connection = (FileConnection) Connector.open(ARTIST_INDEX_FOLDER);
			Enumeration dirsEnum = connection.list();

			while (dirsEnum.hasMoreElements()) {
				String currentFolder = (String) dirsEnum.nextElement();
				handleFolder(currentFolder);
			}

			connection.close();
		} catch (IOException e) {
			Boot.alertException(e, this, "setup()");
		}
	}

	// Folders are named after artists
	public void handleFolder(String folder) {
		String key = folder.substring(0, 2).toLowerCase();

		if (!index.containsKey(key)) {
			artist = new Artist(folder);
			index.put(key, new ChainArtist(artist, null, null));
		} else {
			storeArtistWithPeers(folder, key);
		}

		// Treatment of special characters
		if (StringUtils.containsSpecialCharacters(key)) {

			if (!index.containsKey("11")) {
				Artist artist = new Artist(folder);
				index.put("11", new ChainArtist(artist, null, null));
			} else {
				storeArtistWithPeers(folder, key);
			}
		}

		// TODO Treatment of "the"
	}

	private void storeArtistWithPeers(String folder, String key) {

		ChainArtist newSibling = null;
		ChainArtist chainCurrent = (ChainArtist) index.get(key);
		boolean stored = false;

		while (!stored) {
			boolean lowerThanCurrent = (chainCurrent.getArtist().getName()
					.toLowerCase().compareTo(artist.getName().toLowerCase()) >= 0);
			// mp3File < current

			if (lowerThanCurrent) {
				newSibling = new ChainArtist(artist,
						chainCurrent.getPrevious(), chainCurrent);
				if (chainCurrent.getPrevious() == null) {
					index.remove(key);
					index.put(key, newSibling);
				} else {
					chainCurrent.getPrevious().setNext(newSibling);
				}
				chainCurrent.setPrevious(newSibling);
				stored = true;
			} else if (chainCurrent.getNext() == null) {
				newSibling = new ChainArtist(artist, chainCurrent, null);
				chainCurrent.setNext(newSibling);
				stored = true;
			}
			chainCurrent = chainCurrent.getNext();
		}
	}

}
